<template>
  <div class="processAndpay">
    <div class="tip" v-if="form.is_allocation == 1">
     油气已分配，分配金额:{{ form.allocation_oil_money }}
    </div>
    <el-form class="fromArea" v-if="Object.keys(form).length > 0" :model="form" :validate-on-rule-change="false"
      :rules="rules" ref="ruleForm" label-width="120px" @keyup.native.enter="toSave">
      <el-form-item label="运单ID">
        <el-input readonly :value="form.add_id + '-' + form.yund_id" placeholder="运单ID"></el-input>
      </el-form-item>

      <el-form-item label="货品名称">
        <el-input v-model="form.goods" placeholder="备注" :readonly="inputDisabled"></el-input>
      </el-form-item>
      <el-form-item label="发货重量(吨)">
        <el-input v-model="form.kg" placeholder="发货重量"></el-input>
      </el-form-item>
      <el-form-item label="收货重量(吨)" prop="shkg">
        <!-- <el-input v-model="form.shkg" placeholder="收货重量" :readonly="inputDisabled"></el-input> -->
        <!-- @change="handleChangeInputNumber1" -->
        <el-input-number v-model="form.shkg" :precision="4" placeholder="收货重量" :step="0.0001" :readonly="inputDisabled"

          ></el-input-number>
      </el-form-item>
      <el-form-item label="运费单价(元)" prop="yfdj">
        <el-input v-model="form.yfdj" placeholder="运费单价" :readonly="inputDisabled"></el-input>
      </el-form-item>
      <el-form-item label="收货人名称">
        <el-input readonly v-model="form.company_name" placeholder="收货人名称"></el-input>
      </el-form-item>
      <el-form-item label="总运费(元)" prop="zyf">
        <el-input class="colorRed" v-model="form.zyf" placeholder="总运费" :readonly="inputDisabled"></el-input>
      </el-form-item>
      <el-form-item label="预支付运费(元)">
        <el-input class="colorRed" readonly v-model="form.pay_money" placeholder="预支付运费"></el-input>
      </el-form-item>
      <el-form-item label="实结金额(元)" prop="real_money">
        <el-input ref="real_money" class="colorRed" v-model="form.real_money" placeholder="实结金额" :readonly="gasDisabled"></el-input>
        <el-button size="mini"  type="primary" @click="clearRest">抹零</el-button>
      </el-form-item>
      <el-form-item label="运费增补(元)">
        <el-input readonly class="colorRed" v-model="form.yfzb" placeholder="运费增补"></el-input>
      </el-form-item>
      <el-form-item label="运费扣减(元)">
        <el-input readonly class="colorRed" v-model="form.yfkj" placeholder="运费扣减"></el-input>
      </el-form-item>
      <el-form-item label="应扣油气成本(元)">
        <el-input v-model="form.oil_money" placeholder="油气价格" readonly></el-input>
        <el-button size="mini" type="primary" @click="setOilDialog = true" :disabled="form.is_allocation == 1" >设置油价</el-button>
      </el-form-item>
      <el-form-item label="增减原因">
        <el-input v-model="form.zbyy" placeholder="增减原因" :readonly="inputDisabled"></el-input>
      </el-form-item>

      <el-form-item label="货物单价(元)">
        <el-input readonly v-model="form.danjia" placeholder="运费单价"></el-input>
      </el-form-item>
      <el-form-item label="车牌号">
        <el-input readonly v-model="form.cph" placeholder="车牌号"></el-input>
      </el-form-item>
      <el-form-item label="首笔支付(元)">
        <el-input readonly class="colorRed" v-model="form.first_payment" placeholder="首笔支付"></el-input>
      </el-form-item>
      <el-form-item label="二次支付(元)">
        <el-input readonly class="colorRed" v-model="form.TwoPayment" placeholder="二次支付"></el-input>
      </el-form-item>
      <el-form-item label="合理亏损(吨)">
        <el-input v-model="form.hlks" placeholder="合理亏损" :readonly="inputDisabled"></el-input>
      </el-form-item>
      <el-form-item label="吨差">
        <!-- <el-input v-model="form.kszl" placeholder="亏损重量"></el-input> -->
        <el-input v-model="weightDiff" placeholder="亏损重量">
          <template slot="prepend">
            <span v-if="symbolDuncha" style="color:green;font-weight: 600;">涨吨</span>
            <span v-else style="color:red;font-weight: 600;">亏损</span>
          </template>
          <template slot="append">
            吨
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="司机名称">
        <el-input readonly v-model="form.driver_name" placeholder="司机名称"></el-input>
      </el-form-item>
      <el-form-item label="联系方式(司机)">
        <el-input readonly v-model="form.mobile" placeholder="司机联系方式"></el-input>
      </el-form-item>
      <el-form-item label="发货地">
        <el-input readonly v-model="form.ship_address" placeholder="发货地"></el-input>
      </el-form-item>
      <el-form-item label="收货地">
        <el-input readonly v-model="form.to_address" placeholder="收货地"></el-input>
      </el-form-item>
      <el-form-item label="收款户名">
        <el-input readonly v-model="form.nhxm" placeholder="收款户名"></el-input>
      </el-form-item>
      <el-form-item label="收款账号">
        <el-input readonly v-model="form.nhk" placeholder="收款账号"></el-input>
      </el-form-item>
      <el-form-item label="开户行">
        <el-input readonly v-model="form.nhkhh" placeholder="开户行"></el-input>
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="form.beizhu" placeholder="备注" ></el-input>
      </el-form-item>
      <el-form-item label="装车费" v-if="form.is_cost == 1">
        <el-input v-model="form.loading_charge" placeholder="装车费" readonly></el-input>
      </el-form-item>
      <el-form-item label="卸车费" v-if="form.is_cost == 1">
        <el-input v-model="form.unloading_charge" placeholder="卸车费" readonly></el-input>
      </el-form-item>
      <el-form-item label="保险费" v-if="form.is_cost == 1">
        <el-input v-model="form.insurance_expense" placeholder="保险费" readonly></el-input>
      </el-form-item>
      <el-form-item label="信息费" v-if="form.is_cost == 1">
        <el-input v-model="form.information_cost" placeholder="信息费" readonly></el-input>
      </el-form-item>
      <el-form-item label="押金" v-if="form.is_cost == 1">
        <el-input v-model="form.deposit_charge" placeholder="押金" readonly></el-input>
      </el-form-item>

      <el-form-item label="备注" style="visibility: hidden;"  v-if="form.is_cost == 1">
        <el-input placeholder="备注"></el-input>
      </el-form-item>
      <!-- <el-form-item label="备注" style="visibility: hidden;">
        <el-input placeholder="备注"></el-input>
      </el-form-item> -->
      <el-form-item label="发货单">
        <el-image style="width: 40%;height: 100px;" :src="form.fhd" fit="fit" :preview-src-list="[form.fhd]"></el-image>
        <div class="imgTool">
          <el-upload class="upload-demo" :action="uploadUrl" :headers="getHeader()" :show-file-list="false"
            :on-success="(res, file) => handleAvatarSuccess(res, file, 'fhd')" :limit="1">
            <el-button size="small" type="primary" v-if="!inputDisabled">上传图片</el-button>
            <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
          </el-upload>

          <!-- <el-button class="btn" size="mini">上传图片</el-button> -->
          <span class="t1">*建议上传 600*410 像素的图片</span>
        </div>
      </el-form-item>
      <el-form-item label="收货单">
        <el-image style="width: 40%;height: 100px;" :src="form.shd" fit="fit" :preview-src-list="[form.shd]"></el-image>
        <div class="imgTool">
          <el-upload class="upload-demo" :action="uploadUrl" :headers="getHeader()" :show-file-list="false"
            :on-success="(res, file) => handleAvatarSuccess(res, file, 'shd')" :limit="1">
            <el-button size="small" type="primary" v-if="!inputDisabled">上传图片</el-button>
            <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
          </el-upload>
          <!-- <el-button class="btn" size="mini">上传图片</el-button> -->
          <span class="t1">*建议上传 600*410 像素的图片</span>
        </div>
      </el-form-item>
      <el-form-item class="toolBtn" v-if="form.xiugai == 0 || [0, 2].includes(form.status)">
        <!-- 该运单发起钉钉审批后不可进行保存修改 -->
        <el-button class="btn" type="primary" @click="toSave" v-if="form.batch_number_ding == '0'">保存</el-button>

        <!-- 支付失败显示支付按钮 -->
        <el-button class="btn" type="primary" @click="toSettle" v-if="form.zffs == 11">货主支付</el-button>
        
        <!-- 已审核未支付 并且未发起钉钉审批状态下显示钉钉审批 -->
        <el-button class="btn" type="primary" @click="toDing" 
          v-if="form.xiugai == 1 && form.status == 0 && form.batch_number_ding == '0'">
          钉钉审批
          </el-button>
        <!-- <el-button class="btn" type="primary" @click="onSubmit">中原大户</el-button> -->
      </el-form-item>
    </el-form>
    <el-dialog top="5vh" class="order-dialog" :title="form.area == 0 ? '中原银行支付' : (form.area == 2 ? '兴业银行支付' : '银行')"
      :close-on-click-modal="false" :visible.sync="dialogVisible" width="50%" append-to-body>
      <OrderSettlement v-if="dialogVisible" :settlementInfo="settlementInfo" @closeDialog="closeDialog" />
    </el-dialog>

    <el-dialog class="order-dialog" title="设置油价"
      :close-on-click-modal="false" :visible.sync="setOilDialog" width="30%" append-to-body >
      <setOilPrice v-if="setOilDialog" :formInfo="form"  @closeDialog="closeOilDialog" />
    </el-dialog>
  </div>
</template>

<script>
import OrderSettlement from "./orderSettlement.vue";
import { orderSettlementInformation, savePaymentBill,paymentBillDetail,approveDing } from "@/api/businessUser/moneyManagment";
import setOilPrice from "./setOilPrice.vue";
import { uploadUrl, getHeader, handleMoney } from "@/utils/tool";
import { getUserInfo } from "@/utils/auth";
import Big from "big.js";
import DingApprove from "./DingApprove.vue";
export default {
  name: "processAndpay",
  components: {
    OrderSettlement,
    setOilPrice
  },
  props: {
    billDetail: {
      type: Object,
      default: {}
    }
  },
  mounted() {
    this.initial()
  },
  computed: {
    //吨差
    weightDiff() {
      if (!this.form.shkg) {
        return
      }
      let shkg = new Big(this.form.shkg);//收货重量
      let kg = new Big(this.form.kg);//发货重量
      let res = shkg.minus(kg).toNumber();
      if (res > 0) {
        this.symbolDuncha = true;
      } else {
        this.symbolDuncha = false;
      }
      return Math.abs(res);
    },
    showAction() {
      //已审核 已支付状态的订单不显示保存和支付按钮
      return this.form.xiugai != 1 || this.form.status != 1;
    }
  },
  data() {
    var validateZYF = (rule, value, callback) => {

      if (value === "") {
        callback();
      } else {
        if (!isNaN(value)) {
          //输入的是数字的话 同步更新到实结金额
          if (Number(this.form.pay_money) >= Number(value)) {
            this.$message.error('总运费不得低于预支付运费!');
            callback();
          }
          if (!(/^\d+(\.\d{0,2})?$/.test(value))) {
            //不是数字
            this.form.zyf = value.substring(0, value.length - 1);
          } else {
            if(this.form.is_cost == 1){
              //减去运输成本
              console.log('减去运输成本');
              
              this.form.real_money = (
                value 
                - Number(this.form.pay_money) 
                - Number(this.form.loading_charge)
                - Number(this.form.unloading_charge)
                - Number(this.form.insurance_expense)
                - Number(this.form.information_cost)
                - Number(this.form.deposit_charge)
                ).toFixed(2);
            }else{
              this.form.real_money = (value - Number(this.form.pay_money)).toFixed(2);
            }
         
          }
          this.moneyCompute(value);
        } else {
          this.form.real_money = '0';
        }
        callback();
      }
    };
    var validateYFDJ = (rule, value, callback) => {

      if (value === "") {
        callback();
      } else {
        if (!isNaN(value)) {
          if (!(/^\d+(\.\d{0,2})?$/.test(value))) {
            this.form.yfdj = value.substring(0, value.length - 1);
            callback();
            return;
          }
          let shkg = new Big(this.form.shkg);//收货重量
          let price = new Big(value);//单价
          //输入的是数字的话 同步更新到实结金额
          let zongjia = price.times(shkg).toNumber();
          // this.form.real_money = zongjia;
          this.form.zyf = zongjia.toFixed(2);
          // this.moneyCompute(zongjia);
        } else {
          this.form.real_money = '0';
        }
        callback();
      }
    };
    var validateSHKG = (rule, value, callback) => {
      if (value === "") {
        callback();
      } else {
        if (!isNaN(value)) {
          // if (!(/^\d+(\.\d{0,4})?$/.test(value))) {
          //   this.form.shkg = value.substring(0, value.length - 1);
          //   callback();
          //   return;
          // }
          let price = new Big(this.form.yfdj);//单价
          let shkg = new Big(value);//收货重量
          //输入的是数字的话 同步更新到实结金额
          let zongjia = price.times(shkg).toNumber();
          // this.form.real_money = zongjia;
          this.form.zyf = zongjia.toFixed(2);
          // this.moneyCompute(zongjia);
        } else {
          this.form.real_money = '0';
        }
        callback();
      }
    };
    var validate_removePoint = (rule, value, callback) => {
      if (value === "") {
        this.form[rule.field] = '0'
        callback();
      } else {
        if (!isNaN(value)) {
          if ((value + '').charAt(value.length - 1) === '.') {//如果是20.替换成20
            this.form[rule.field] = value.replace('.', '');
          }
          if (/^0+/.test(value)) {//如果是0000.1替换成0.1
            this.form[rule.field] = value.replace(/^0+/, '0');
          }

          if (/^0+(?!0)(\d+(\.\d+)?)?$/.test(value)) {//如果是0002.1替换成2.1
            this.form[rule.field] = value.replace(/^0+/, '');
          }
        }
        callback();
      }
    };

    const validateRealMoney = (rule, value, callback) => {

      if (value === "") {
        callback();
      }else{
        if (!isNaN(value)) {
          //数字
          let zyf = Number(this.form.zyf);
          let real_money = Number(value);
          let oil_money = Number(this.form.oil_money);
          if(oil_money != 0){//存在油气价格时不进行增补 扣减计算
            callback();
            return;
          }
          if((real_money + oil_money) >= zyf){
            //运费增补
            this.form.yfzb = (real_money + oil_money) - zyf;
            this.form.yfkj = 0;
          }else{
            //运费扣减
            this.form.yfkj = zyf - (real_money + oil_money);
            this.form.yfzb = 0;
          }
          callback();
        }else{
          //非数字
          callback();
        }
      }
    };


    return {
      initialZYF: 0, //初始总运费
      uploadUrl,
      getHeader,
      dialogVisible: false,
      form: {},
      rules: {
        zyf: [{ validator: validateZYF, trigger: "change" }, { validator: validate_removePoint, trigger: "blur" }],
        yfdj: [{ validator: validateYFDJ, trigger: "change" }, { validator: validate_removePoint, trigger: "blur" }],
        shkg: [{ validator: validateSHKG, trigger: "change" }, { validator: validate_removePoint, trigger: "blur" }],
        real_money: [{ validator: validateRealMoney, trigger: "blur" },{ validator: validate_removePoint, trigger: "blur" }],
        // real_money: [{ validator: validateRealMoney, trigger: "change" },{ validator: validate_removePoint, trigger: "blur" }],
      },
      //结算信息
      settlementInfo: {},
      inputDisabled: false,
      gasDisabled:false,
      symbolDuncha: false,//true是正,false是负
      setOilDialog:false,
    };
  },
  methods: {
    initial(refresh = false){
      // this.form = obj;
      if(!refresh){
        this.form = this.billDetail;
      }
      // this.form.oil_money = '66';
      if (this.form.xiugai != 1 || this.form.status != 1) {
        //未审核未支付状态
        if(this.form.oil_money != '0'){
          //存在油气价格 此时总运费不可编辑，实结金额可以编辑，且总运费 = 实结金额 + 油气 + 运费扣减/增补
          this.inputDisabled = true;
          this.gasDisabled = false;
          let zyf = Number(this.form.zyf);
          let real_money = Number(this.form.real_money);
          let oil_money = Number(this.form.oil_money);
          // if((real_money + oil_money) >= zyf){
          //   //运费增补
          //   this.form.yfzb = (real_money + oil_money) - zyf;
          // }else{
          //   //运费扣减
          //   this.form.yfkj = zyf - (real_money + oil_money);
          // }
          this.$nextTick(()=>{
            setTimeout(()=>{
              this.$refs.real_money.$el.querySelector("input").focus()
            },500)
          })
          
        }else{
          //按照之前逻辑不变 存在油气价格时 不可修改实结金额

          this.inputDisabled = false;
          this.gasDisabled = true;

        }
      } else {
        this.inputDisabled = true;
      }
      this.initialZYF = this.form.zyf;
      /**
       * area
       * 0：中原银行
       * 1：无
       * 2: 兴业银行
       * **/
    },
    enterEvt(event){
      if (event.keyCode === 13) {
      // 在这里写入回车键被按下时的逻辑代码
        this.toSave();
      }
    },
    async closeOilDialog(oil_money){
      this.setOilDialog = false;
      let result = await paymentBillDetail({id:this.form.id})
      if(result.code == 200){
        this.form = result.data;
      }
      this.initial(true);
    },
    closeDialog() {
      this.dialogVisible = false;
      this.$emit("closeDialog");
    },
    //抹零
    clearRest() {
      let zyfObj = handleMoney(this.form.zyf)
      this.form.zyf = zyfObj.number;
      let real_moneyObj = handleMoney(this.form.real_money)
      
      this.form.real_money = real_moneyObj.number;

      //将抹零的金额计算到运费扣减上
      setTimeout(()=>{
        this.form.yfkj = this.form.yfkj + real_moneyObj.restNum;
      },0)
    },
    //费用增补，扣减
    moneyCompute(num) {
      this.initialZYF = Number(this.initialZYF);
      num = Number(num);
      if (num >= this.initialZYF) {
        //增补
        this.form.yfzb = (num - this.initialZYF).toFixed(2);
        this.form.yfkj = 0;
      } else {
        //扣减
        this.form.yfkj = (this.initialZYF - num).toFixed(2);
        this.form.yfzb = 0;
      }
    },
    handleAvatarSuccess(res, file, type) {
      if (res.code == 200) {
        this.form[type] = res.data.url;
      }
    },
    async toSave() {
      if (Number(this.form.pay_money) >= Number(this.form.zyf)) {
        this.$message.error('总运费不得低于预支付运费!');
        return
      };
      let {
        yund_id,
        shkg,
        kg,
        yfzb,
        zbyy,
        yfkj,
        khyy,
        yfdj,
        hlks,
        zyf,
        kszl,
        beizhu,
        fhd,
        shd,
        id,
        oil_money,
      } = this.form;

      //存在油气价格 重新计算总运费
      if(this.form.is_oil == 1){
        if(this.form.oil_money != '0'){
          // if(this.form.yfkj){
          //   let yfkj = Number(this.form.yfkj);
          //   zyf = Number(zyf);
          //   zyf = zyf - yfkj;
          // }
          // if(this.form.yfzb){
          //     let yfzb = Number(this.form.yfzb);
          //     zyf = Number(zyf);
          //     zyf = zyf + yfzb;
          // }
          let real_money = Number(this.form.real_money);
          let oil_money = Number(this.form.oil_money);
          zyf = real_money + oil_money;
        }
      }

      let option = {
        yund_id,
        shkg,
        kg,
        yfzb,
        zbyy,
        yfkj,
        khyy,
        yfdj,
        hlks,
        zyf,
        kszl,
        beizhu,
        fhd,
        shd,
        id
      };
      if(this.form.is_oil == 1){
        option = {
          ...option,
          oil_money
        }
      }
      let result = await savePaymentBill(option);
      if (result.code == 200) {
        this.$message.success(result.msg);
        setTimeout(() => {
          this.$emit("closeDialog");
        }, 500);
      } else {
        this.$message.error(result.msg);
      }
    },
    async toDing(){
      this.$confirm('确定要发起钉钉审批吗？', '系统提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
              let obj = {};
              obj.applicant = getUserInfo().name;
              obj.goods = this.form.goods;
              obj.weight = this.form.shkg;
              obj.money = this.form.zyf;
              obj.bill_number = 1;
              obj.yund_id = this.form.yund_id;
              obj.company = this.form.company_name;
              let result = await approveDing(obj);
              if(result.code == 200){
                this.$message({
                  type: 'success',
                  message: '发起成功!'
                });
                setTimeout(()=>{ 
                  this.closeDialog();
                },500)
              }
            }).catch(() => { });
      
    },
    async toSettle() {
      if (this.form.xiugai == 0) {
        this.$message.error('该运单还未审核,无法进行支付!');
        return;
      }

      const loading = this.$loading({
        lock: true,
        text: "Loading...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.5)",
        customClass: "loadingCss"
      });
      let result = await orderSettlementInformation({
        id: this.form.yund_id
      });
      loading.close();
      if (result.code == 200) {
        this.settlementInfo = {
          ...result.data,
          area: this.form.area,
          shkg: this.form.shkg,
          yund_id: this.form.yund_id,
          sj_id: this.form.sj_id,
          shd: this.form.shd,
          fhd: this.form.fhd,
          first_payment: this.form.first_payment,
          yfdj: this.form.yfdj,
          zyf: this.form.zyf,
          is_first_payment: this.form.is_first_payment,
        };
        // first_payment: this.form.first_payment,
        if (Number(result.data.money) < Number(result.data.real_money)) {
          this.$message.error('账户余额不足!')
          return;
        }
        this.dialogVisible = true;
      }
    },
    onSubmit() { }
  },
  created(){
    //添加保存按钮的回车事件
    document.removeEventListener('keyup',this.enterEvt);
    document.addEventListener('keyup',this.enterEvt);
  },
  beforeDestroy(){
    // console.log('我要销毁啦');
    document.removeEventListener('keyup',this.enterEvt);
  }
};
</script>

<style lang="scss" scoped>
.processAndpay {
  height: 100%;
  overflow: auto;
  .loadingCss {
    font-size: 50px;
  }
  .tip{
    text-align: center;
    color:red;
    margin-bottom: 10px;
  }
  .fromArea {
    display: flex;
    flex-wrap: wrap;

    .colorRed {
      ::v-deep .el-input__inner {
        color: $theme-Danger;
      }
    }

    .el-form-item {
      width: 30%;
      margin-right: 20px;
    }

    .toolBtn {
      width: 100%;
      // flex: 1;
      display: flex;
      justify-content: center;
      margin-top: 30px;

      .btn {
        width: 100px;
      }

      ::v-deep .el-form-item__content {
        margin-left: 0 !important;
      }
    }
  }

  ::v-deep .el-dialog__header {
    padding-top: 10px;
    padding-left: 20px;
  }

  ::v-deep .el-dialog {
    height: 60vh;

    .el-dialog__body {
      max-height: 500px;
      overflow: auto;
    }
  }

  ::v-deep .el-input-number {
    width: 100%;

    .el-input-number__decrease {
      display: none;
    }

    .el-input-number__increase {
      display: none;
    }

    .el-input__inner {
      text-align: left;
      padding-left: 15px
    }
  }

  ::v-deep .el-form-item__content {
    display: flex;

    .imgTool {
      display: flex;
      flex-direction: column;
      align-items: center;
      flex: 1;

      .btn {
        width: 80px;
      }

      .t1 {
        margin-left: 10px;
        color: $theme-Danger;
      }
    }

    .el-select {
      width: 100%;
    }

    .el-input {
      width: 100%;
    }

    .el-button {
      margin-left: 10px;
      // background-color: $theme-primary;
      // color: #fff;
      // border: none;
      max-height: 40px;
      // border-radius: 20px;
    }
  }
}
</style>
